import React, { useState, useEffect } from 'react';
import { Spin, message, Typography } from 'antd';
import { InfoCircleOutlined } from '@ant-design/icons';
import { CustomFrame } from '../components/CustomFrame';
import { useNavigate } from 'react-router-dom';
import { getMainAppConfig, getCurrentUserInfo } from '../services/mainApp';
import { getCurrentAccount, refreshCurrentAccount } from '../services/account';
import { UserInfoCard } from '../components/UserInfoCard/UserInfoCard';
import { AccountPoolCard } from '../components/AccountPoolCard/AccountPoolCard';
import { UtilsCard } from '../components/UtilsCard/UtilsCard';
import { UserInfo, QuotaInfo } from '../types/mainApp';
import { AccountInfo } from '../types/account';
import { AxiosError } from 'axios';
import styles from './MainApp.module.css';

export const MainApp: React.FC = () => {
    const navigate = useNavigate();
    const [notice, setNotice] = useState('');
    const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
    const [accountInfo, setAccountInfo] = useState<AccountInfo | null>(null);
    const [loading, setLoading] = useState({ notice: true, user: true, account: true });

    const fetchUser = async () => {
        setLoading(prev => ({ ...prev, user: true }));
        try {
            const response = await getCurrentUserInfo();
            if (response.data.data) {
                setUserInfo(response.data.data);
            }
        } catch (error) {
            console.error("加载用户信息失败:", error);
            const axiosError = error as AxiosError;
            if (axiosError.response?.status === 401) {
                message.error('会话已过期，请重新登录');
                handleLogout();
            }
        } finally {
            setLoading(prev => ({ ...prev, user: false }));
        }
    };

    const fetchAccount = async () => {
        setLoading(prev => ({ ...prev, account: true }));
        try {
            const response = await getCurrentAccount();
            if (response.data.data) {
                setAccountInfo(response.data.data);
            }
        } catch (error) {
            console.error("加载账号信息失败:", error);
        } finally {
            setLoading(prev => ({ ...prev, account: false }));
        }
    };

    const handleActivationSuccess = (newQuotaInfo: QuotaInfo) => {
        setUserInfo(currentUserInfo => {
            if (!currentUserInfo) return null;
            return {
                ...currentUserInfo,
                quotaInfo: newQuotaInfo,
            };
        });
    };

    useEffect(() => {
        const fetchNotice = async () => {
            setLoading(prev => ({ ...prev, notice: true }));
            try {
                const response = await getMainAppConfig();
                if (response.data.data.app_notice) {
                    setNotice(response.data.data.app_notice);
                }
            } catch (error) {
                console.error("加载公告失败:", error);
            } finally {
                setLoading(prev => ({ ...prev, notice: false }));
            }
        };

        fetchNotice();
        fetchUser();
        fetchAccount();
    }, []);

    const handleAccountSwapped = () => {
        message.info('账号已切换，正在刷新用户信息...');
        fetchUser();
        fetchAccount();
    };

    const handleRefreshAccount = async () => {
        message.loading({ content: '正在刷新...', key: 'refresh' });
        try {
            await refreshCurrentAccount();
            const response = await getCurrentAccount();
            if (response.data.data) {
                setAccountInfo(response.data.data);
                message.success({ content: '刷新成功!', key: 'refresh' });
            } else {
                setAccountInfo(null);
                message.warning({ content: '刷新成功，但获取最新信息失败', key: 'refresh' });
            }
        } catch (error) {
            console.error("刷新账号失败:", error);
            const axiosError = error as AxiosError<{ message: string }>;
            message.error({ content: axiosError.response?.data?.message || '刷新失败', key: 'refresh' });
        }
    }

    const handleLogout = async () => {
        await window.electronAPI.runTask('store:delete', 'token');
        navigate('/login');
    };

    return (
        <CustomFrame title="CursorTool">
            <div style={{ }}>
                {loading.notice ? (
                    <div style={{ display: 'flex', justifyContent: 'center', margin: '24px 0' }}>
                        <Spin />
                    </div>
                ) : (
                    notice && (
                        <div className={styles.customNotice}>
                            <InfoCircleOutlined className={styles.noticeIcon} />
                            <span>{notice}</span>
                        </div>
                    )
                )}
                
                <UserInfoCard 
                    userInfo={userInfo} 
                    loading={loading.user} 
                    onLogout={handleLogout}
                    onActivationSuccess={handleActivationSuccess}
                />
                
                <AccountPoolCard
                    accountInfo={accountInfo}
                    loading={loading.account}
                    onRefresh={handleRefreshAccount}
                />
                
                <UtilsCard onSuccess={handleAccountSwapped} />

                <div className={styles.footer}>
                    <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                        Copyright © {new Date().getFullYear()} Codeera. All Rights Reserved.
                    </Typography.Text>
                </div>
            </div>
        </CustomFrame>
    ); 
}; 